<template>
  <div class="login-container">
    <div class="login-box">
      <h2>{{ isLogin ? '系统登录' : '用户注册' }}</h2>
      <form @submit.prevent="handleSubmit">
        <div class="form-group">
          <label for="username">用户名</label>
          <input 
            type="text" 
            id="username" 
            v-model="username" 
            required 
            placeholder="请输入用户名"
          >
        </div>
        <div class="form-group">
          <label for="password">密码</label>
          <input 
            type="password" 
            id="password" 
            v-model="password" 
            required 
            placeholder="请输入密码"
          >
        </div>
        <div v-if="!isLogin" class="form-group">
          <label for="confirmPassword">确认密码</label>
          <input 
            type="password" 
            id="confirmPassword" 
            v-model="confirmPassword" 
            required 
            placeholder="请再次输入密码"
          >
        </div>
        <div v-if="error" class="error-message">
          {{ error }}
        </div>
        <button type="submit" :disabled="loading">
          {{ loading ? (isLogin ? '登录中...' : '注册中...') : (isLogin ? '登录' : '注册') }}
        </button>
        <div class="switch-form">
          <a href="#" @click.prevent="switchForm">
            {{ isLogin ? '没有账号？立即注册' : '已有账号？立即登录' }}
          </a>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const username = ref('')
const password = ref('')
const confirmPassword = ref('')
const loading = ref(false)
const error = ref('')
const isLogin = ref(true)

const switchForm = () => {
  isLogin.value = !isLogin.value
  error.value = ''
  password.value = ''
  confirmPassword.value = ''
}

const handleSubmit = async () => {
  if (!isLogin.value && password.value !== confirmPassword.value) {
    error.value = '两次输入的密码不一致'
    return
  }

  loading.value = true
  error.value = ''
  
  try {
    const endpoint = isLogin.value ? 'http://127.0.0.1:5000/api/login' : 'http://127.0.0.1:5000/api/register'
    console.log('Sending request to:', endpoint)
    
    const response = await fetch(endpoint, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
      body: JSON.stringify({
        username: username.value,
        password: password.value,
      }),
    })

    console.log('Response status:', response.status)
    const contentType = response.headers.get('content-type')
    console.log('Response content type:', contentType)

    if (!response.ok) {
      let errorMessage
      if (contentType && contentType.includes('application/json')) {
        const data = await response.json()
        errorMessage = data.message
      } else {
        const text = await response.text()
        console.error('Error response:', text)
        errorMessage = `服务器错误 (${response.status})`
      }
      throw new Error(errorMessage || (isLogin.value ? '登录失败' : '注册失败'))
    }

    if (!contentType || !contentType.includes('application/json')) {
      throw new Error('服务器返回了无效的响应格式')
    }

    const data = await response.json()
    console.log('Response data:', data)
    
    if (isLogin.value) {
      // 存储用户信息和token
      localStorage.setItem('token', data.token)
      localStorage.setItem('username', data.user.username)
      localStorage.setItem('userRole', data.user.role)
      
      // 根据用户角色跳转到不同页面
      if (data.user.role === 'admin') {
        router.push('/users')
      } else {
        router.push('/recognition')
      }
    } else {
      // 注册成功后切换到登录界面
      isLogin.value = true
      error.value = '注册成功，请登录'
    }
  } catch (err) {
    console.error('Error details:', err)
    error.value = err.message || '操作失败，请稍后重试'
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f5f5;
}

.login-box {
  background: white;
  padding: 2rem;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 400px;
}

h2 {
  text-align: center;
  color: #2c3e50;
  margin-bottom: 2rem;
}

.form-group {
  margin-bottom: 1.5rem;
}

label {
  display: block;
  margin-bottom: 0.5rem;
  color: #666;
}

input {
  width: 100%;
  padding: 0.8rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
}

input:focus {
  outline: none;
  border-color: #42b983;
}

button {
  width: 100%;
  padding: 0.8rem;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 1rem;
  cursor: pointer;
  transition: background-color 0.3s;
}

button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

button:hover:not(:disabled) {
  background-color: #3aa876;
}

.error-message {
  color: #c62828;
  background-color: #ffebee;
  padding: 0.8rem;
  border-radius: 4px;
  margin-bottom: 1rem;
  text-align: center;
}

.switch-form {
  text-align: center;
  margin-top: 1rem;
}

.switch-form a {
  color: #42b983;
  text-decoration: none;
}

.switch-form a:hover {
  text-decoration: underline;
}
</style> 